import os
from service.sjxz import zddr_upload


def run(llq, hszz, xmlb, nd, folderpath):
  os.makedirs(folderpath, exist_ok=True)
  browser, context, page = llq
  page.click('#toolbar_header_function')
  page.fill('#search', '组织核算项目定义')
  page.wait_for_timeout(2000)
  try:
      page.wait_for_selector('ul.search--result-list', timeout=2000)
  except Exception:
      page.click('.header--search')
  page.locator('ul.search--result-list li').first.click()

  page.click('#textBox_accOrgID .f-icon-lookup')
  page.locator('.lookup-tabs-content [name="input-group-value"]').fill(hszz)
  page.locator('.lookup-tabs-content [name="input-group-value"]').press('Enter')
  page.wait_for_timeout(1000)
  page.locator('[id^=rownode] .align-items-center span:text-matches(\"^'+hszz+'$\")').last.dblclick()

  page.click('#textBox_year .f-icon-lookup')
  page.locator('.lookup-tabs-content [title="'+nd+'"]').dblclick()

  page.click('#textBox_categoryID .f-icon-lookup')
  page.locator('.lookup-tabs-content [title="'+xmlb+'"]').dblclick()

  page.locator('#button-sure').last.click()
  page.locator('#button-export').last.click()

  page.wait_for_selector('li.borderactive[title="核算项目导出"]')
  id = page.query_selector('.borderactive a').get_attribute('id')
  page.wait_for_selector("iframe#rtf_iframe_" + id[:-5])
  frame = page.query_selector("iframe#rtf_iframe_" + id[:-5]).content_frame()

  with page.expect_download(timeout=600000) as download_info:
    frame.click('[toolbarid="baritem_export"]')
    frame.click('.lee-dialog-table label[for="exportNewSet-1"]')
    frame.click('.lee-dialog-buttons .lee-btn-primary')
    download = download_info.value
    filepath = os.path.join(folderpath, nd+xmlb+'导出'+download.suggested_filename[-5:])
    download.save_as(filepath)
  zddr_upload.file_uploads(filepath)
  page.click('[title="核算项目导出"] div.nav-link-close')
  page.click('[title="组织核算项目定义"] div.nav-link-close')



